package tmt.usercenter.web.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tmt.usercenter.web.domain.TmtOauthAccount;
import tmt.usercenter.web.domain.enums.TmtOauthType;
import tmt.usercenter.web.domain.TmtUser;
import tmt.usercenter.web.repository.ITmtAuthorityRepo;
import tmt.usercenter.web.repository.ITmtOauthAccountRepo;

import java.util.*;

/**
 * 公共账号服务
 * Created by Stark on 2017/3/10.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TmtOauthAccountService extends TmtBaseService<TmtOauthAccount, Long> {

	@Getter
	private ITmtOauthAccountRepo tmtOauthAccountRepo;

	@Autowired
	public TmtOauthAccountService(ITmtOauthAccountRepo tmtOauthAccountRepo){
		super(tmtOauthAccountRepo, new ArrayList<>());
		this.tmtOauthAccountRepo = tmtOauthAccountRepo;
	}

	/**
	 * 是否存在 oauth 账号
	 *
	 * @param type    类型
	 * @param oauthId 本地账号
	 * @return 是否存在关联的 oauth 账号
	 */
	@Transactional(readOnly = true)
	public boolean existsOauthAccount(TmtOauthType type, String oauthId) {
		return tmtOauthAccountRepo.existsByAuthTypeAndAuthId(type, oauthId);
	}

	/**
	 * 绑定第三方账号到用户
	 *
	 * @param user    绑定到的内部账号
	 * @param type    第三方账号类型
	 * @param oauthId 第三方账号
	 * @param details 第三方账号相关细节
	 */
	@Transactional(readOnly = true)
	public void bindOauth(TmtUser user, TmtOauthType type, String oauthId, Map<String, String> details) {
		TmtOauthAccount oauthAccount = new TmtOauthAccount();
		oauthAccount.setEnabled(true);
		oauthAccount.setAuthType(type);
		oauthAccount.setCreateTime(new Date());
		oauthAccount.setTmtUser(user);
		oauthAccount.setAuthId(oauthId);

		ObjectMapper mapper = new ObjectMapper();
		oauthAccount.setDetail(mapper.valueToTree(details));

		tmtOauthAccountRepo.save(oauthAccount);
	}

	@Transactional(readOnly = true)
	public List<TmtOauthAccount> findByUserId(Long userId) {
		return tmtOauthAccountRepo.findAllByTmtUserId(userId);
	}

	@Transactional(readOnly = true)
	public TmtUser findUserByAuthTypeAndAuthId(TmtOauthType oauthType, String authId){
		return tmtOauthAccountRepo.findTmtUserByAuthTypeAndAuthId(oauthType, authId);
	}

	/*@PreAuthorize("#oauthAccount.tmtUser.username == principal.username")
	public void disableOrEnableOauthAccount(TmtOauthAccount oauthAccount, boolean enabled) {
		tmtOauthAccountRepo.disableOrEnableOauthAccount(oauthAccount.getId(), enabled);
	}

	@PreAuthorize("#oauthAccount.appUser.username == principal.username")
	public void delete(TmtOauthAccount oauthAccount) {
		tmtOauthAccountRepo.delete(oauthAccount);
	}*/
}
